import { z } from 'zod'
import { Spacer } from '@/components/ui/spacer'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { User } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { useNavigate } from 'react-router-dom'
import { useContext } from 'react'
import { AuthContext } from './layout'

const schema = z.object({
  idCard: z.string().refine(
    (val) => {
      const idCardRegex =
        /^[1-9]\d{5}(19\d{2}|20[0-2]\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
      return idCardRegex.test(val)
    },
    { message: '请输入有效的18位身份证号' },
  ),
})

export default function LoginView() {
  const navigate = useNavigate()
  const { setIdCard } = useContext(AuthContext)

  const form = useForm<z.infer<typeof schema>>({
    resolver: zodResolver(schema),
    defaultValues: { idCard: '' },
  })

  const handleSubmit = (values: z.infer<typeof schema>) => {
    setIdCard?.(values.idCard)
    navigate('/face')
  }

  return (
    <div className='flex flex-col items-center w-full h-full'>
      <div className='flex flex-col cursor-pointer'>
        <div className='text-base leading-none text-foreground'>身份证登录</div>
        <Spacer className='h-2' />
        <div className='w-full h-0.5 bg-[#2666FF]'></div>
      </div>
      <Spacer className='h-6' />
      <Form {...form}>
        <form
          className='flex flex-col justify-between w-full h-full'
          onSubmit={form.handleSubmit(handleSubmit)}
        >
          <FormField
            control={form.control}
            name='idCard'
            render={({ field }) => (
              <FormItem className='space-y-3'>
                <FormLabel
                  htmlFor='idCard'
                  className='flex items-center space-x-1'
                >
                  <User className='size-4 text-accent-foreground' />
                  <span className='text-foreground text-xs'>身份证号</span>
                </FormLabel>
                <div className='bg-background rounded-lg border border-border'>
                  <FormControl>
                    <Input
                      id='idCard'
                      {...field}
                      placeholder='请输入您的身份证号'
                      autoComplete='username'
                      inputMode='numeric'
                      className='px-4 py-3 bg-transparent text-foreground placeholder:text-muted-foreground border-none rounded-lg'
                    />
                  </FormControl>
                </div>
                <FormMessage />
              </FormItem>
            )}
          />
          <Button>登录</Button>
        </form>
      </Form>
    </div>
  )
}
